package com.efounder.frame.fragment;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.core.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.efounder.frame.bean.FilterBean;
import com.efounder.frame.bean.FilterNodeBean;
import com.efounder.frame.filter.FilterInterface;
import com.efounder.mobilemanager.R;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;


/**
 * create by meijun
 */
@Deprecated
public class FilterFragment extends DialogFragment implements AdapterView.OnItemClickListener {

    private ArrayList<FilterNodeBean> filterNodeBeans;
    private View view;
    private static final String TAG = "FilterFragment";
    private int dialogDefaultWidth;
    private int dialogDefaultHeight;
    private FrameLayout filterFrameLayout;
    private ListView filterListView;
    // private FlexboxLayout flexboxLayout;
    private ScrollView filterScrollView;
    private int top;
    private int marginTop = 0;
    // private FrameLayout fileterListViewContainer;
    private LinearLayout linear;

    public FilterFragment() {
    }

    public FilterFragment(ArrayList<FilterNodeBean> filterNodeBeans) {
        this.filterNodeBeans = filterNodeBeans;
        FilterNodeBean bean = new FilterNodeBean(getResources().getString(R.string.common_text_cancel));
        bean.setSql("test");
        filterNodeBeans.add(bean);
    }

    public void onStart() {
        super.onStart();

        resetWindwoSize();
    }

    private void resetWindwoSize() {

        Window window = this.getDialog().getWindow();
        WindowManager.LayoutParams params = window.getAttributes();

        params.width = dialogDefaultWidth;
        params.height = dialogDefaultHeight + marginTop;
        params.y = (int) getResources().getDimension(R.dimen.ef_title_view_height);
        params.gravity = Gravity.TOP | Gravity.RIGHT;
        window.setAttributes(params);
        window.setBackgroundDrawable(new ColorDrawable(0));
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initData();
    }

    public TextView createTextView(View childView) {
        if (childView == null) {
            TextView textView = (TextView) LayoutInflater.from(getContext()).inflate(R.layout.filter_textview, null);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            params.gravity = Gravity.CENTER_HORIZONTAL;
            params.topMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, 3, getResources().getDisplayMetrics());
            int pd10 = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, getResources().getDisplayMetrics());
            params.setMargins(pd10, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 3, getResources().getDisplayMetrics()), pd10, 0);
            textView.setLayoutParams(params);
            textView.setPadding(pd10, pd10, pd10, pd10);
            textView.setBackgroundColor(Color.WHITE);
            textView.setTextColor(Color.parseColor("#333333"));
            return textView;

        } else {

            //将textview初始化;
            TextView textView = (TextView) childView;
            textView.setBackgroundColor(Color.WHITE);
            textView.setTextColor(Color.parseColor("#333333"));
            textView.setVisibility(View.VISIBLE);
            return textView;
        }

    }


    @Nullable
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        this.getDialog().requestWindowFeature(1);
        this.view = inflater.inflate(R.layout.fragment_filter, container, true);
        return this.view;
    }

    private void initData() {
        dialogDefaultWidth = (getActivity().getWindowManager().getDefaultDisplay().getWidth());
        dialogDefaultHeight = ((Float) (dialogDefaultWidth / 1.2f)).intValue();
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initFindView(view);


        inflateData();

        registerListener();
        hiddenSubView();
    }


    private void registerListener() {
        filterListView.setOnItemClickListener(this);
    }

    int lastPosition = 0;
    int currentPosition = -1;
    View lastView = null;

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (lastView != null) {
            lastView.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.white));
        }

        currentPosition = position;
        lastPosition = position;
        lastView = view;

        view.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.filter_text_color));

        FilterNodeBean bean = filterNodeBeans.get(position);
        if (bean.isHaveChild()) {
            showSubView();
            addChildTextView(bean);
        } else {
            hiddenSubView();
            if (position == filterNodeBeans.size() - 1) {
                //恢复未过滤状态
                FilterBean bean1 = new FilterBean();
                bean1.type = 0;
                EventBus.getDefault().post(bean1);
                dismiss();
                return;
            }
            buttonclick(bean.getSql());
        }
        View inflate = LayoutInflater.from(getActivity()).inflate(android.R.layout.simple_list_item_1, null);
        ((TextView) inflate).setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
        int heightd = inflate.getHeight();


    }

    /**
     * 将子孩子添加subView面板
     *
     * @param bean 孩子他爹
     */
    private void addChildTextView(FilterNodeBean bean) {

        int childCount = linear.getChildCount();

        List<FilterNodeBean> childNodes = bean.getChildNodes();

        for (int i = 0; i < childNodes.size(); i++) {

            final FilterNodeBean child = childNodes.get(i);

            View childView = linear.getChildAt(i);

            TextView textView = createTextView(childView);

            //将孩子添加到subview上;
            if (textView.getParent() == null) {
                linear.addView(textView, i);
            }

            String textColor = child.getTextColor();
            if (!TextUtils.isEmpty(textColor)) {
                try {
                    textView.setTextColor(Color.parseColor(textColor));

                } catch (IllegalArgumentException e) {

                    Log.e(TAG, "颜色配置不正确" + e.toString());
                }
            }

            String bgColor = child.getBgColor();

            if (!TextUtils.isEmpty(bgColor)) {
                try {

                    textView.setBackgroundColor(Color.parseColor(bgColor));
                } catch (IllegalArgumentException e) {
                    Log.e(TAG, "颜色配置不正确" + e.toString());
                }
            }

            textView.setText(child.getName());
            textView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    buttonclick(child.getSql());
                }
            });
        }

        //隐藏不使用的子孩子
        for (int j = childNodes.size(); j < childCount; j++) {
            linear.getChildAt(j).setVisibility(View.INVISIBLE);
        }

    }


    private void showSubView() {
        filterScrollView.setVisibility(View.VISIBLE);
    }

    private void hiddenSubView() {
        filterScrollView.setVisibility(View.INVISIBLE);
    }

    private void inflateData() {

        filterListView.setAdapter(new ArrayAdapter<FilterNodeBean>(getContext(),
                android.R.layout.simple_list_item_1, filterNodeBeans) {
            @NonNull
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {


                TextView tv = (TextView) super.getView(position, convertView, parent);
                tv.setGravity(Gravity.CENTER);
                tv.setBackgroundColor(Color.WHITE);
                tv.setTextColor(Color.parseColor("#333333"));
                if (currentPosition == position) {
                    tv.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.filter_text_color));
                }

                tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
                tv.setText(filterNodeBeans.get(position).getName());
                return tv;
            }
        });

        filterListView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                int height = filterListView.getChildAt(0).getHeight();
                dialogDefaultHeight = height * 5;
                resetWindwoSize();
                filterListView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
        });
    }

    private void initFindView(View view) {


        filterListView = (ListView) view.findViewById(R.id.fileterListView);


        filterScrollView = (ScrollView) view.findViewById(R.id.fileterScrollView);

        linear = (LinearLayout) view.findViewById(R.id.linearlayout);
    }

    public void buttonclick(String sql) {

        ((FilterInterface) getActivity()).beginFilter(sql);
        dismiss();
    }


    public void dd(int top) {
        this.top = top;
    }
}


